﻿Imports Microsoft.VisualBasic
Imports log4net
Imports System.Web.Script.Serialization

Public Class JsonTools
    Private Shared ReadOnly log As ILog = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)

    Public Shared Function JsonToDictionaryObject(ByVal json As String) As Dictionary(Of String, Object)
        Dim obj As Dictionary(Of String, Object) = Nothing
        Try
            json = json.Trim
            Dim strCompare As String = "{" & """TABLE"":["
            If Left(json, 10).ToUpper.Equals(strCompare) Then
                json = json.Remove(0, 10)
                If Right(json, 2).Equals("]}") Then
                    json = Left(json, json.Length - 2)
                End If
            End If

            Dim deserializer As New JavaScriptSerializer()
            obj = deserializer.Deserialize(Of Dictionary(Of String, Object))(json)
        Catch ex As Exception
            log.Error(ex)
            log.Info("JsonInfo: " & json)
        End Try
        Return obj
    End Function

    Public Shared Function DictionaryObjectToJson(ByVal dicObj As Dictionary(Of String, Object)) As String
        Dim strJson As String = ""
        Try
            If dicObj IsNot Nothing Then
                Dim deserializer As New JavaScriptSerializer()
                strJson = deserializer.Serialize(dicObj)
            End If
            
        Catch ex As Exception
            log.Error(ex)
        End Try
        Return strJson
    End Function

    Public Shared Function ObjectToJson(ByVal objectValue As Object) As String
        Dim strJson As String = ""
        Try
            If objectValue IsNot Nothing Then
                Dim deserializer As New JavaScriptSerializer()
                strJson = deserializer.Serialize(objectValue)
            End If

        Catch ex As Exception
            log.Error(ex)
        End Try
        Return strJson
    End Function

    Public Shared Function JsonToObject(ByVal strJson As String) As ArrayList
        Dim objResult As ArrayList = Nothing
        Try
            If strJson IsNot Nothing AndAlso Not strJson.Trim.Equals("") Then
                Dim deserializer As New JavaScriptSerializer()
                objResult = deserializer.Deserialize(Of ArrayList)(strJson)
            End If

        Catch ex As Exception
            log.Error(ex)
        End Try
        Return objResult
    End Function

End Class
